package com.simple.base.controller;

import com.simple.base.common.result.CommonResult;
import com.simple.base.common.utils.ResultUtils;
import com.simple.base.core.domain.response.SysMenuResponse;
import com.simple.base.core.repository.entity.SysMenu;
import com.simple.base.core.repository.entity.extend.SysMenuExtend;
import com.simple.base.core.service.ISysMenuService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author kin
 * @since 2017/12/21
 */
@RestController
@RequestMapping("/api/sys/menu")
public class SysMenuController {

    @Autowired
    private ISysMenuService sysMenuService;

    @RequiresPermissions(value = "sys:menu:list")
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public CommonResult list() {
        List<SysMenuExtend> userMenuList = sysMenuService.getUserMenuList(1L);
        return ResultUtils.ok(parse(userMenuList, true));
    }

    private List<SysMenuResponse> parse(List<SysMenuExtend> menuList, boolean isGroup) {
        if(CollectionUtils.isEmpty(menuList)){
            return  Collections.emptyList();
        }

        List<SysMenuResponse> list = new ArrayList<>();

        menuList.forEach(x -> {
            SysMenuResponse sysMenuResponse = new SysMenuResponse();
            if (isGroup) {
                sysMenuResponse.setGroup(true);
            }
            sysMenuResponse.setText(x.getName());
            sysMenuResponse.setIcon(x.getIcon());
            sysMenuResponse.setLink(x.getLink());
            sysMenuResponse.setChildren(parse(x.getList(), false));
            list.add(sysMenuResponse);
        });
        return list;
    }
}
